#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@NAME          : mcinsta.py
@TIME          : 2024/11/16 21:24:58
@AUTHOR        : chenlip
@VERSION       : 0.0.1
@DESCRIPTION   : 配置类
'''
# --------------------------引用--------------------------
import os, datetime, json
# --------------------------引用--------------------------

class Config:
    # 项目base目录
    APPLICATION_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
    CURYEAR = datetime.datetime.now().strftime('%Y') # 当前年份
    CURDAY = datetime.datetime.now().strftime('%Y-%m-%d') # 当天
    CURTIME = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') # 当前时间
    CURMONTH = datetime.datetime.now().strftime('%Y-%m') # 当前月份
    YESTERDAY = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime('%Y-%m-%d') # 昨天
    DEBUG = False
    TESTING = False
    SECRET_KEY = 'hoeking#1234567890'
    WTF_CSRF_TIME_LIMIT = 3600

    # Session配置 必须增加，否则可能出现不可预料的问题；
    SESSION_COOKIE_PATH = '/'
    SESSION_COOKIE_NAME = 'yourong_bbs_session'
    SESSION_COOKIE_DOMAIN = None
    SESSION_COOKIE_SECURE = False
    
    OPENAI_API_KEY = 'your_openai_api_key_here'
    # SSE配置
    SSE_SIGNATURE_KEY = 'yourong-bXZETBmit34yAud9Smyn' # SSE签名密钥
    # Flask-JWT配置
    JWT_SECRET_KEY = 'yourong#1975' # JWT密钥
    JWT_ACCESS_TOKEN_EXPIRES = datetime.timedelta(days=1) # JWT访问令牌有效期
    JWT_REFRESH_TOKEN_EXPIRES = datetime.timedelta(days=360) # JWT刷新令牌有效期
    JWT_HEADER_TYPE = 'JWT' # JWT头部类型
    # JWT_BLACKLIST_ENABLED = True # JWT黑名单启用
    # JWT_BLACKLIST_TOKEN_CHECKS = ['access', 'refresh'] # JWT黑名单检查

    # Flask-login配置
    REMEMBER_COOKIE_NAME = 'yourong_bbs_remember_token' # cookie 名称
    # REMEMBER_COOKIE_DOMAIN = '.yourong.cc' # cookie 域名
    REMEMBER_COOKIE_DURATION = datetime.timedelta(days=30) # cookie 有效期
    REMEMBER_COOKIE_SECURE = False # cookie 安全,Cookie只在HTTPS连接中发送
    # REMEMBER_COOKIE_HTTPONLY = True # cookie 只读, 不能被js读取
    REMEMBER_COOKIE_SAMESITE = 'Lax' # cookie 同源

    # minio 配置
    MINIOCONF = {
        'endpoint': 'minio.51epub.com', # minio 服务器地址
        'access_key': 'admin', # bXZETBmit34yAud9Smyn
        'secret_key': 'hoeking#1975' # Xre8CslOqRrYvN9j4UirWxuOZcOH2lQB0KEvWskE
    }
    # 阿里云 oss 配置
    ALIYUN_OSS = {
        'enable': 'on',
        'endpoint': 'oss-cn-hangzhou.aliyuncs.com',
        'AccessKeyID': 'LTAI5tEdvE1NGWsjkgEki4vY',
        'AccessKeySecret': 'oZcVnDHRhJSceYMspX9k9U4oaYgIRd',
        'bucket_name': 'mdblog',
        'basicdir': '51epub.com',
        'blogimgurl': '51epub.com/mdimages/blog/',
        'coveimgurl': '51epub.com/mdimages/blog/bookcover/',
        'defaultCover': 'https://mdblog.oss-cn-hangzhou.aliyuncs.com/51epub.com/mdimages/blog/bookcover/51epub_cover.png',
        'defaultsm': 'https://mdblog.oss-cn-hangzhou.aliyuncs.com/51epub.com/mdimages/blog/bookcover/51epub_cover-sm.png'
    }
    # ALIGO 云盘配置
    ALIGO_CONF = {
        'refresh_token': 'your_refresh_token_here'
    }

    # 百度网盘配置
    BAIDUPAN = {
        'appid': '25405734',
        'client_id': 'VY0KsnjQa4UfqPoGEHx7K8jmFKa1rt5y',
        'client_secret': 'cTN5gmZNX2sxxaPerSYSTAqIwU0IOgdt',
        'sign_key': 'JwziKS~l4Baaq+utyeH=4*',
        'auth_code': 'ec4c3a404d1452dd044f2cda6273b29d',
        'token_json_fn': os.path.join(os.path.dirname(__file__), 'baidupan_token.json')
    }

    # CORS 跨域配置
    CORSSITES = [
        'http://127.0.0.1',
        'http://localhost',
        'http://192.168.1.186',
        'http://192.168.1.189',
        'http://192.168.1.122',
        'http://192.168.1.166',
        'https://minio.51epub.com',
        'https://www.51epub.com',
        'https://51epub.com',
        'https://chenlp.cc'
    ]
    # 系统的临时缓存目录
    TEMPDIR = os.path.join(APPLICATION_ROOT, 'static/temps')
    # 系统资源目录
    COMROOTRES = os.path.join(APPLICATION_ROOT, 'logs')
    # 城通网盘, token 三天有效,access_key 一年有效
    CTWP = {
        'enable': 'on',
        'access_key': '5362250126fac3f3f564435a24655b21',
        'token': 'af62ac7411f7e6440a4533f31bac049',
        'phone': '13971114872',
        'root_fd_id': '48012053',
        'dl_pass': '9685'
    }
    # 重试次数和暂停时间
    NET_CONN = {
        'net_max_retries': 3, # 网络连接次数
        'net_sleep': 5 # 暂停时间, 单位秒
    }

    # 日志配置
    # %(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s
    LOGCONF = {
        'logfilepath': os.path.join(APPLICATION_ROOT, 'logs'),
        'logfileprefix': 'dev',
        'when': 'D',
        'backCount': 2,                 # 开发环境只保留2天日志
        'format': '%(asctime)s - %(custom_filename)s[line:%(custom_lineno)d] - %(levelname)s: %(message)s',
        'logisscreen': 1,               # 开发环境输出到控制台
        'logencode': 'utf-8',
        'loglevel': 'debug'             # 开发环境记录所有日志
    }

    # Mysql8配置
    MYSQL8 = {
        'host': '192.168.1.189',
        'port': 5308,
        'user': 'root',
        'password': 'mysql#1975',
        'database': 'yourong_bbs',
        'charset': 'utf8mb4'
    }
    #SQLALCHEMY_DATABASE_URI = 'sqlite:///your_database.db'
    SQLALCHEMY_DATABASE_URI = f'mysql+pymysql://{MYSQL8["user"]}:{MYSQL8["password"]}@{MYSQL8["host"]}:{MYSQL8["port"]}/{MYSQL8["database"]}?charset={MYSQL8["charset"]}'
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SQLALCHEMY_ECHO = False
    SQLALCHEMY_ENGINE_OPTIONS = {
        'pool_size': 20,                # 连接池大小
        'pool_recycle': 280,            # 连接回收时间(秒)
        'pool_timeout': 30,             # 连接池获取超时时间
        'pool_pre_ping': True,          # 连接前ping一下
        'connect_args': {
            'charset': 'utf8mb4',       # 使用utf8mb4字符集
            'use_unicode': True,         # 使用unicode
            'time_zone': '+00:00'       # 使用UTC时区
        }
    }

    # CDNJSON配置
    _CDNDICT = {}
    with open(os.path.join(APPLICATION_ROOT, 'static', 'cdn.json'), 'r', encoding='utf-8') as f:
        _CDNDICT = json.load(f)

    # CDNboot
    CDNBOOT = _CDNDICT['CDNBOOT'] if 'CDNBOOT' in _CDNDICT else {}
    # CDNZStatic
    CDNZS = _CDNDICT['CDNZS'] if 'CDNZS' in _CDNDICT else {}
    # CDNMC
    CDNMC = _CDNDICT['CDNMC'] if 'CDNMC' in _CDNDICT else {}

    # 启用CDN
    ENABLECDN = _CDNDICT['ENABLECDN'] if 'ENABLECDN' in _CDNDICT else 'CDNMC'

    # 新增数据库位置配置
    DB_PATH = os.path.join(APPLICATION_ROOT, 'data')
    
    # 确保数据目录存在
    if not os.path.exists(DB_PATH): os.makedirs(DB_PATH)

    # 速率限制配置
    IP_WHITELIST = [
        '127.0.0.1',
        '192.168.1.166',
        '192.168.1.122',
        '192.168.1.186',
        '192.168.1.189'
    ]
    RATELIMIT = {
            'login': (30, 5),
            'register': (60, 3),
            'normal': (5, 15),
            'api': (5, 30),
            'resource': (10, 8),
            'admin': (10, 15)
        }


class DevelopmentConfig(Config):
    DEBUG = True
    REMEMBER_COOKIE_SECURE = False
    # minio 配置
    MINIOCONF = {
        'endpoint': '192.168.1.186:9000', # minio 服务器地址
        'access_key': 'admin',
        'secret_key': 'hoeking#1975'
    }
    # 替换为SQLite配置
    SQLALCHEMY_DATABASE_URI = f'sqlite:///{os.path.join(Config.DB_PATH, "yourong_bbs.db")}'
    
    # SQLite特定配置
    SQLALCHEMY_ENGINE_OPTIONS = {
        'connect_args': {
            'check_same_thread': False  # 允许多线程访问
        }
    }
    

class TestingConfig(Config):
    TESTING = True
    REMEMBER_COOKIE_SECURE = False
    # minio 配置
    MINIOCONF = {
        'endpoint': '192.168.1.186:9000', # minio 服务器地址
        'access_key': 'admin',
        'secret_key': 'hoeking#1975'
    }
    # 替换为SQLite配置
    SQLALCHEMY_DATABASE_URI = f'sqlite:///{os.path.join(Config.DB_PATH, "yourong_bbs.db")}'
    # SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
    
    # SQLite特定配置
    SQLALCHEMY_ENGINE_OPTIONS = {
        'connect_args': {
            'check_same_thread': False  # 允许多线程访问
        }
    }

class ProductionConfig(Config):
    # minio 配置
    MINIOCONF = {
        'endpoint': 'minio.51epub.com', # minio 服务器地址
        'access_key': 'admin',
        'secret_key': 'hoeking#1975'
    }
    # SQLALCHEMY_DATABASE_URI = 'mysql://user:password@localhost/prod_database'

    # 生成环境日志配置
    LOGCONF = {
        'logfilepath': '/var/log/wemedia',  # 生产环境使用标准日志路径
        'logfileprefix': 'wemedia',
        'when': 'D',
        'backCount': 7,                # 生产环境保留7天日志
        'format': '%(asctime)s - %(name)s - %(levelname)s: %(message)s',
        'logisscreen': 0,               # 生产环境不输出到控制台
        'logencode': 'utf-8',
        'loglevel': 'info'              # 生产环境只记录info及以上级别
    }

# 配置字典
conf = {
    'dev': DevelopmentConfig,
    'test': TestingConfig,
    'prod': ProductionConfig
}